package com.example.juc.kkb.locksupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    public static void main(String[] args) {

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        List<String> list = new ArrayList<>();

        new Thread(() -> {
            //如果把下⾏这句代码打开,先signal后await,会出现A线程⼀直处于等待状态
//            try {
//                TimeUnit.SECONDS.sleep(3);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "coming....");
                // condition.await执行后，当前线程A会释放掉锁，其他线程执行Condition.signal()，当前线程A会重新获得锁，继续执行
                condition.await();
                // 直到线程B调用signal方法后，才执行下面这行代码往list中添加元素
//                list.add("线程A");
//                System.out.println(Thread.currentThread().getName() + "\t" + "被唤醒");
//                System.out.println("list 线程A: " + list);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                System.out.println(Thread.currentThread().getName() + "\t" + "进入finally");
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "END....");
        }, "A").start();

        new Thread(() -> {
            lock.lock();
//            System.out.println(Thread.currentThread().getName() + "\t" + "线程获得锁");
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "唤醒A线程。。。");
                // 在此处输出的list是空的，意味着在线程A中的await方法执行后，直接走了finally释放了锁，并没有往list集合中添加元素
//                System.out.println("list 线程B: " + list);
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "B").start();
    }
}